package com.hsnn.medstgmini.trading.pur.dao.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.trading.pur.dao.OrderConfirmDao;
import com.hsnn.medstgmini.trading.pur.model.OrderDetailStatus;
import com.hsnn.medstgmini.trading.pur.model.OrderPackStatus;
import com.hsnn.medstgmini.trading.pur.model.form.OrderPackage;
import com.hsnn.medstgmini.util.AreaUtil;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 配送企业订单确认
 * @author 蔡春龙
 * @date 2015年7月13日
 */
@Repository
public class OrderConfirmDaoImpl implements OrderConfirmDao {

	@Resource(name = "sessionFactory")
	private SessionFactory factory;
	
	@Autowired
	private HibernateSqlUtil dao;

	/**
	 * @category 分页查询订单包信息
	 * @date 2015年7月13日
	 * @param orderPackage
	 * @param page
	 * @return
	 */
	public Pagination getOrderConfirm(OrderPackage orderPackage, Pagination page) {
		Session session = factory.getCurrentSession();
		StringBuffer hql = new StringBuffer();
		hql.append("select config_value from sys_purconfig where  config_id = '999432a1-23d0-11e5-9cc0-40f2e9d2c708' ");
		SQLQuery configQuery = session.createSQLQuery(hql.toString());
		Object obj = configQuery.uniqueResult();
		
		
		StringBuilder sb = new StringBuilder();
		sb.append(" SELECT a.remarks,a.order_pack_id orderPackId, a.hosp_code hospCode, a.hosp_name hospName,  ");
		sb.append(" a.hosp_ar_fullname hospArFullname, a.count, a.amount, a.is_urgent isUrgent, ");
		sb.append(" a.submit_datetime submitDatetime, ");
		sb.append(" a.recp_addr recpAddr, a.recp_userphone recpUserphone, a.recp_user recpUser ");
		sb.append(" FROM pur_orderpack a WHERE a.del_comp_code = :delCompCode ");
		sb.append(" AND a.order_status = :orderStatus  ");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("delCompCode", orderPackage.getDelCompCode());
		params.put("orderStatus", orderPackage.getOrderStatus());
		
		if (StringUtils.isNotBlank(orderPackage.getHospName())) {
			sb.append(" AND ( a.hosp_name LIKE :hospName OR a.hosp_spel_code LIKE :hospName ) ");
			params.put("hospName", "%" + orderPackage.getHospName() + "%");
		}
		
		if (StringUtils.isNotBlank(orderPackage.getAreaId())) {
			sb.append(" AND a.hosp_area_id LIKE :areaId ");
			params.put("areaId", AreaUtil.escapeAreaId(orderPackage.getAreaId()));
		}
		
		if (StringUtils.isNotBlank(orderPackage.getOrderPackId())) {
			sb.append(" AND a.order_pack_id = :orderPackId ");
			params.put("orderPackId", orderPackage.getOrderPackId());
		}
				
		if (orderPackage.getStartDate() != null) {
			sb.append(" AND DATE_FORMAT(a.submit_datetime, '%Y-%m-%d') >= :startDate ");
			params.put("startDate", DateUtil.date(orderPackage.getStartDate()));
		}
		
		if (orderPackage.getEndDate() != null) {
			sb.append(" AND DATE_FORMAT(a.submit_datetime, '%Y-%m-%d') <= :endDate ");
			params.put("endDate", DateUtil.date(orderPackage.getEndDate()));
		}
		
		if(obj != null){
			sb.append(" AND a.order_conf_end_time >= SYSDATE() ");
		}
		sb.append(" order by a.submit_datetime DESC ");
		return dao.getPageMapList(sb.toString(), params, page);
	}
	
	/**
	 * @category 查询订单包信息
	 * @date 2015年7月13日
	 * @param op
	 * @param page
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> getOrderPackageById(String id) {
		Session session = factory.getCurrentSession();
		
		StringBuilder sb = new StringBuilder();
		sb.append(" SELECT a.remarks,a.order_pack_id orderPackId, a.hosp_code hospCode, a.hosp_name hospName,  ");
		sb.append(" a.hosp_ar_fullname hospArFullname, a.count, a.amount, ");
		sb.append(" a.submit_datetime submitDatetime, ");
		sb.append(" a.order_confirm_time orderConfirmTime, ");
		sb.append(" a.recp_addr recpAddr, a.recp_userphone recpUserphone, a.recp_user recpUser ");
		
		sb.append(" FROM pur_orderpack a WHERE a.order_pack_id = :orderPackId ");
		
		SQLQuery query = session.createSQLQuery(sb.toString());
		query.setString("orderPackId", id);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		
		return (Map<String, Object>) query.uniqueResult();
	}

	/**
	 * @category 配送企业分页按包查询订单明细列表
	 * @date 2015年7月13日
	 * @param orderPackage
	 * @param page
	 * @return
	 */
	public Pagination getOrderConfirmDetail(OrderPackage orderPackage,
			Pagination page) {
		StringBuilder sb = new StringBuilder();
		sb.append(" SELECT a.order_code orderCode, a.order_pack_id orderPackId, ");
		sb.append("     a.pro_count proCount, a.del_count delCount, a.pro_price proPrice,  ");
		sb.append("     a.join_plan_time joinPlanTime, a.join_plan_user joinPlanUser,  ");
		sb.append("     a.order_status orderStatus, a.confirm_remark confirmRemark,  ");
		sb.append("     a.goods_code goodsCode, a.area_name areaName, a.pro_count * a.pro_price orderMoney, ");
		sb.append("     a.ar_shortname arShortname, a.ar_fullname arFullname,  ");
		sb.append("     a.proj_id projId, a.proj_name projName, a.proj_starttime projStarttime,  ");
		sb.append("     a.proj_endtime projEndtime, a.proj_status projStatus,  ");
		sb.append("     a.drug_code drugCode, a.qualityspec_name drugName,  ");
		sb.append("     a.form_name formName, a.spec_name specName, a.bus_name busName,  ");
		sb.append("     a.factor, a.unit_name unitName, a.material_name materialName,  ");
		sb.append("     a.prod_compcode prodCompcode, a.prod_compname prodCompname,  ");
		sb.append("     a.prod_compstatus prodCompstatus,   a.cat_comp_code catCompCode,  ");
		sb.append("     a.cat_comp_name catCompName, a.cat_comp_status catCompStatus,  ");
		sb.append("     a.use_range useRange, a.drug_attr drugAttr, a.goods_source goodsSource,  ");
		
		
		sb.append("     a.pattern_type patternType, a.is_healthcare isHealthcare,  ");
		sb.append("     a.is_agriculture isAgriculture, a.is_lowprice isLowprice,  ");
		sb.append("     a.is_smallprice isSmallprice, a.is_smallsource isSmallsource,  ");
		sb.append("     a.is_longtime_plan isLongtimePlan, a.drug_status drugStatus,  ");
		sb.append("     a.drug_cat drugCat, a.pro_price_limit proPriceLimit,  ");
		sb.append("     a.retail_price_limit retailPriceLimit, a.hang_price hangPrice,  ");
		sb.append("     a.ref_price refPrice, a.healthcare_price healthcarePrice,  ");
		sb.append("     a.pic_url picUrl, a.pic_short_url picShortUrl,a.drug_medicine drugMedicine, a.status,b.recp_count recpCount  ");
		sb.append(" FROM pur_orderinfo a left join pur_delorderinfo b on a.order_code = b.order_code  where a.order_pack_id = :orderPackId ");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderPackId", orderPackage.getOrderPackId());
		
		if (orderPackage.getOrderStatus() != null) {
			sb.append(" AND (a.order_status = :orderStatus or a.order_status=:shortStatus)");
			params.put("orderStatus", orderPackage.getOrderStatus());
			params.put("shortStatus", OrderDetailStatus.shortDrug.getKey());
		}
		
		if (StringUtils.isNotBlank(orderPackage.getDrugName())) {
			sb.append(" AND (a.qualityspec_name LIKE :drugName OR a.qualityspec_name_spel LIKE :drugName) ");
			params.put("drugName", "%" + orderPackage.getDrugName() + "%");
		}
		
		if (StringUtils.isNotBlank(orderPackage.getDrugCode())) {
			sb.append(" AND a.drug_code = :drugCode ");
			params.put("drugCode", orderPackage.getDrugCode());
		}
		
		if (StringUtils.isNotBlank(orderPackage.getCompName())) {
			sb.append(" AND (a.prod_compname LIKE :compName OR a.prod_compname_spel LIKE :compName) ");
			params.put("compName", "%" + orderPackage.getCompName() + "%");
		}
		if(StringUtils.isNotBlank(page.getConditions().get("NoPage"))) {
			page.setRows(dao.getSqlMapList(sb.toString(), params));
			return page;
		}else {
			return dao.getPageMapList(sb.toString(), params, page);
		}
	}
	
	/**
	 * @category 分页按包查询订单明细列表
	 * @date 2015年7月13日
	 * @param orderPackage
	 * @param page
	 * @return
	 */
	public Pagination getOrderConfirmDetailDel(OrderPackage orderPackage,
			Pagination page) {
		StringBuilder sb = new StringBuilder();
		sb.append(" SELECT a.order_code orderCode, a.order_pack_id orderPackId, ");
		sb.append("     a.pro_count proCount,a.drug_medicine drugMedicine,a.del_count delCount, a.pro_price proPrice,  ");
		sb.append("     a.join_plan_time joinPlanTime, a.join_plan_user joinPlanUser,  ");
		sb.append("     a.order_status orderStatus, a.confirm_remark confirmRemark,  ");
		sb.append("     a.goods_code goodsCode, a.area_name areaName, a.pro_count * a.pro_price orderMoney, ");
		sb.append("     a.ar_shortname arShortname, a.ar_fullname arFullname,  ");
		sb.append("     a.proj_id projId, a.proj_name projName, a.proj_starttime projStarttime,  ");
		sb.append("     a.proj_endtime projEndtime, a.proj_status projStatus,  ");
		sb.append("     a.drug_code drugCode, a.qualityspec_name drugName,  ");
		sb.append("     a.form_name formName, a.spec_name specName, a.bus_name busName,  ");
		sb.append("     a.factor, a.unit_name unitName, a.material_name materialName,  ");
		sb.append("     a.prod_compcode prodCompcode, a.prod_compname prodCompname,  ");
		sb.append("     a.prod_compstatus prodCompstatus, a.cat_comp_code catCompCode,  ");
		sb.append("     a.cat_comp_name catCompName, a.cat_comp_status catCompStatus,  ");
		sb.append("     a.use_range useRange, a.drug_attr drugAttr, a.goods_source goodsSource,  ");
		sb.append("     a.pattern_type patternType, a.is_healthcare isHealthcare,  ");
		sb.append("     a.is_agriculture isAgriculture, a.is_lowprice isLowprice,  ");
		sb.append("     a.is_smallprice isSmallprice, a.is_smallsource isSmallsource,  ");
		sb.append("     a.is_longtime_plan isLongtimePlan, a.drug_status drugStatus,  ");
		sb.append("     a.drug_cat drugCat, a.pro_price_limit proPriceLimit,  ");
		sb.append("     a.retail_price_limit retailPriceLimit, a.hang_price hangPrice,  ");
		sb.append("     a.ref_price refPrice, a.healthcare_price healthcarePrice,  ");
		sb.append("     a.pic_url picUrl, a.pic_short_url picShortUrl, a.status,a.prod_compname_spel,a.qualityspec_name_spel,SUM(b.recp_count) recpCount  ");
		sb.append(" FROM pur_orderinfo a left join pur_delorderinfo b on a.order_code = b.order_code where a.order_pack_id = :orderPackId GROUP BY a.goods_code ");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderPackId", orderPackage.getOrderPackId());
		
		if (orderPackage.getOrderStatus() != null) {
			sb.append(" AND (a.order_status = :orderStatus or a.order_status=:shortStatus)");
			params.put("orderStatus", orderPackage.getOrderStatus());
			params.put("shortStatus", OrderDetailStatus.shortDrug.getKey());
		}
		
		if (StringUtils.isNotBlank(orderPackage.getDrugName())) {
			sb.append(" AND (a.qualityspec_name LIKE :drugName OR a.qualityspec_name_spel LIKE :drugName) ");
			params.put("drugName", "%" + orderPackage.getDrugName() + "%");
		}
		
		if (StringUtils.isNotBlank(orderPackage.getDrugCode())) {
			sb.append(" AND a.drug_code = :drugCode ");
			params.put("drugCode", orderPackage.getDrugCode());
		}
		
		if (StringUtils.isNotBlank(orderPackage.getCompName())) {
			sb.append(" AND (a.prod_compname LIKE :compName OR a.prod_compname_spel LIKE :compName) ");
			params.put("compName", "%" + orderPackage.getCompName() + "%");
		}
		if(StringUtils.isNotBlank(page.getConditions().get("NoPage"))) {
			page.setRows(dao.getSqlMapList(sb.toString(), params));
			return page;
		}else {
			return dao.getPageSelectMapList(sb.toString(), params, page);
		}
	}

	/**
	 * @category 确认或拒绝
	 * @date 2015年11月25日
	 * @param orderPackIds
	 * @param user
	 * @param type1确认0拒绝
	 */
	public void dispatch(String orderPackIds, SysUser user, int type) {
		String[] ids = orderPackIds.split(",");
		int orderPackStatus = OrderPackStatus.finishOrder.getKey();
		int orderDetailStatus = OrderDetailStatus.decline.getKey();
		if (type == 1) {
			orderPackStatus = OrderPackStatus.confirmed.getKey();
			orderDetailStatus = OrderDetailStatus.confirmed.getKey();
		}
		if (ids != null && ids.length > 0) {
			//	更新订单表状态
			StringBuilder sb = new StringBuilder();
			sb.append(" UPDATE pur_orderpack SET order_status = :orderStatus, order_confirm_user = :userId, ");
			sb.append(" order_confirm_time = SYSDATE() WHERE order_pack_id IN (:ids) ");
			
			Session session = factory.getCurrentSession();
			SQLQuery query = session.createSQLQuery(sb.toString());
			query.setParameterList("ids", ids);
			query.setString("userId", user.getId());
			query.setInteger("orderStatus", orderPackStatus);
			query.executeUpdate();
			
			//	更新订单明细状态
			sb = new StringBuilder();
			sb.append(" UPDATE pur_orderinfo SET order_status = :orderStatus WHERE order_pack_id IN (:ids) ");
			
			query = session.createSQLQuery(sb.toString());
			query.setParameterList("ids", ids);
			query.setInteger("orderStatus", orderDetailStatus);
			query.executeUpdate();
			
			session.flush();
		}
	}
	
	/**
	 * @category 根据订单明细号查询配送信息列表
	 * @date 2015年7月13日
	 * @param orderPackage
	 * @param page
	 * @return
	 */
	public Pagination getOrderDelList(OrderPackage orderPackage, Pagination page) {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT a.del_detail_id delDetailId, a.order_pack_id orderPackId, a.order_code orderCode,  ");
		sb.append(" a.del_count delCount, b.`name` delUser, a.approve_code approveCode, ");
		sb.append(" DATE_FORMAT(a.del_datetime, '%Y-%m-%d %T') delDatetime,  ");
		sb.append(" a.is_recepted isRecepted, a.recp_count recpCount, c.`name` recpUser,  ");
		sb.append(" DATE_FORMAT(a.recp_datetime, '%Y-%m-%d %T') recpDatetime,  ");
		sb.append(" a.invoice_no invoiceNo, a.invoice_amount invoiceAmount,  ");
		sb.append(" DATE_FORMAT(a.invoice_datetime, '%Y-%m-%d') invoiceDatetime,a.credential ");
		sb.append(" FROM pur_delorderinfo a  ");
		sb.append(" LEFT JOIN sys_user b ON a.del_user = b.id ");
		sb.append(" LEFT JOIN sys_user c ON a.recp_user = c.id ");
		sb.append(" WHERE a.order_code = :orderCode ");

		Session session = factory.getCurrentSession();
		SQLQuery query = session.createSQLQuery(sb.toString());
		query.setString("orderCode", orderPackage.getOrderCode());
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		
		page.setRows(query.list());
		return page;
	}

}
